package com.aldobucchi.alias
{

	import flash.events.Event;
	import flash.events.EventDispatcher;
	
	import com.aldobucchi.ds.container.zet.IOSet;
	import com.aldobucchi.ds.container.zet.IOWSet;
	import com.aldobucchi.ds.container.zet.impl.owSet;
	import com.aldobucchi.ds.op.ContainerBiggestOp;
	import com.aldobucchi.utils.IOperator;


	public class AliasRecord extends EventDispatcher
	{



		/////////////////////////////////////////
		// context
		/////////////////////////////////////////

		private var _context:AliasContext;
		public function get context( ):AliasContext
		{
			return _context;
		}



		/////////////////////////////////////////
		// element
		/////////////////////////////////////////

		private var _element:*;
		public function get element( ):*
		{
			return _element;
		}




		/////////////////////////////////////////
		// cannonical
		/////////////////////////////////////////

		private var _cannonical:*;
		[Bindable("change")]
		public function get cannonical( ):*
		{
			return _cannonical;
		}



		/////////////////////////////////////////
		// aliases
		/////////////////////////////////////////
		
		internal var _aliases:IOWSet;
		public function get aliases( ):IOSet
		{
			return _aliases;
		}



		/////////////////////////////////////////
		// etc...
		/////////////////////////////////////////


		private var op:IOperator;



		/////////////////////////////////////////
		// constructor
		/////////////////////////////////////////
	

		public function AliasRecord( element:*, context:AliasContext )
		{
		
			_element = element;
			_cannonical = element;
			_context = context;
			
			_aliases = owSet( [ element ] );
			
			op = new ContainerBiggestOp( _aliases, context.compareFunction, setCannonical, null ); 			
			
		}




		
		internal function reset( ):void
		{
			_aliases.autoUpdateFlag.disable( );
			
				_aliases.clear();
				_aliases.add( _element );
			
			_aliases.autoUpdateFlag.enable( );
		
		}
		


		
		private function setCannonical( e:* ):void
		{
		
			if ( e == null )
				e = _element;
				
			if ( _cannonical === e ) // no change
				return;
				
			_cannonical = e;
			
			dispatchEvent( new Event( Event.CHANGE ) );		
		
		}




		
	}
}